package com.xwder.nio.groupchat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 群聊客户端
 *
 * @author xwder
 * @date 2021/3/18 10:17
 **/
public class GroupChatClient {

    private static final Logger logger = LoggerFactory.getLogger(GroupChatClient.class);

    private Selector selector;

    private SocketChannel socketChannel;

    private static final String HOST = "127.0.0.1";

    private static final int PORT = 6666;

    private String clientName;

    public GroupChatClient() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            clientName = socketChannel.getLocalAddress().toString().substring(1);
            logger.info("群聊系统客户端初始化成功~~~");
        } catch (IOException e) {
            logger.error("群聊系统客户端初始化失败", e);
        }
    }

    /**
     * 接收服务器端的消息
     */
    public void readServerSendData() {
        try {
            int selectCount = selector.select();
            if (selectCount > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        //得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array(),StandardCharsets.UTF_8);
                        logger.info("接收到服务器端消息:{}", msg);
                    }
                    // 删除当前的selectionKey, 防止重复操作
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            logger.error("接收到服务器端消息发送错误", e);
        }
    }

    /**
     * 往服务器端发送消息
     *
     * @param msg
     */
    public void sendMsgToServer(String msg) {
        msg = clientName + "说:" + msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            logger.error("客户端发送消息到服务器端失败", e);
        }
    }

    public static void main(String[] args) {
        GroupChatClient groupChatClient = new GroupChatClient();
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    groupChatClient.readServerSendData();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            groupChatClient.sendMsgToServer(s);
        }
    }
}
